package com.sixth.util;

import com.sixth.bean.common.BaseRespVo;
import com.sixth.exception.CustomValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * @Author lixinhang
 * @Time 2022/9/10 14:30
 * 参数校验的工具类
 */
public class ValidationUtils {

    public static BaseRespVo getBaseRespVo(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();//获取校验错误
            String field = fieldError.getField();   //拿到成员变量名->请求参数名
            Object rejectedValue = fieldError.getRejectedValue();   //拿到错误的数字
            String defaultMessage = fieldError.getDefaultMessage(); //拿到消息

            StringBuffer sb = new StringBuffer();
            sb.append(field).append("的值").append(rejectedValue).append("离谱:").append(defaultMessage);
            BaseRespVo baseRespVo = BaseRespVo.invalidParameter(sb.toString());
            baseRespVo.setErrno(402);
            return baseRespVo;
        }
        return null;
    }

    //为了只让做参数校验时只写一行代码
    public static void valid(BindingResult bindingResult) throws CustomValidationException {
        if(bindingResult.hasFieldErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            String field = fieldError.getField();//获取校验未通过的成员变量
            Object rejectedValue = fieldError.getRejectedValue();//获取校验未通过的参数
            String defaultMessage = fieldError.getDefaultMessage();//获取错误信息
            StringBuffer sb = new StringBuffer();
            sb.append("参数").append(field).append("传入了错误的值").append(rejectedValue).append(":").append(defaultMessage);
            throw new CustomValidationException(sb.toString());
        }
    }
}
